package application;
import dataStructures.*;

/**
 * @author Carlos Duarte - 43796
 * @author Rafael Florencio - 43829
 */
public class TextClass implements Text {
	
	private enum TYPE{
		E, C, P
	}
	
	private static final long serialVersionUID = 0L;
	private Line[] Lines;
	private int countLines;
	private Dictionary<String, Word> words;
	private String id;
	private Dicionario textDicionario;
	
	public TextClass(String idText, int numLinhas, Dicionario dicionario){
		Lines = new Line[numLinhas];
		words = new AVLTree<String, Word>();
		id = idText;
		textDicionario = dicionario;
		countLines = 0;
	}

	@Override
	public String GetID() {
		return id;
	}
	@Override
	public void addLine(String Rline, int line) {
		Word aux = null;
		String[] auxWord = Rline.trim().split(" +");
		if(!auxWord[0].isEmpty()){
			for(String val:auxWord){
				aux = words.find(val.toLowerCase());
				if(aux != null){
					aux.SetTime(countLines+1);
				}
				else
					words.insert(val.toLowerCase(), new WordClass(val.toLowerCase(), GetWordState(val), countLines+1));
			}
		}
		Lines[countLines++] = new LineClass(Rline);
	}

	@Override
	public String GetWordState(String Rword) {
		// TODO Auto-generated method stub
		if(textDicionario.verifyWord(Rword))
			return "C";
		return "E";
	}
	
	@Override
	public String getLine(int position) {
		// TODO Auto-generated method stub
		return Lines[position-1].getLine();
	}

	@Override
	public String getText(int minimumLine, int maximumLine) {
		String msg="";
		if(maximumLine!=0)
		{
			for(int i=minimumLine;i<=maximumLine;i++)
			{
				if(i==maximumLine)
					msg+=getLine(i);
				else
					msg+=getLine(i)+"\n";
			}

		}
		else
		{
			for(int i=minimumLine;i<=countLines;i++)
			{
				if(i==countLines)
					msg+=getLine(i);
				else
					msg+=getLine(i)+"\n";
			}
		}
		return msg;
	}
	
	public Iterator<Word> listWordByType(String type){
		Iterator<Entry<String, Word>> it = words.iterator();
		Word aux;
		DoublyLinkedList<Word> wordType = new DoublyLinkedList<Word>();
		if(type.equals("P")){
			while(it.hasNext()){
				wordType.addLast(it.next().getValue());
			}
		}
		else{
			while(it.hasNext()){
				aux = it.next().getValue();
				if(aux.GetType().equals(type)){
					wordType.addLast(aux);
				}
			}
		}
		return wordType.iterator();
	}
		

	@Override
	public int countWord(String Rword) {
		Word aux = words.find(Rword.toLowerCase());
		if(aux != null)
			return aux.countTimes();
		else
			return 0;
		
	}

	@Override
	public boolean hasWord(String word) {
		if(words.find(word.toLowerCase()) != null)
			return true;
		else
			return false;
	}
	
	@Override
	public int getnLines() {
		// TODO Auto-generated method stub
		return countLines;
	}

}
